import axios from 'axios'
import { useUserStore } from '@/stores/user'

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      const userStore = useUserStore()
      userStore.logout()
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户相关API
export const login = (username: string, password: string) => {
  return api.post('/auth/login/', { username, password })
}

export const register = (userData: any) => {
  return api.post('/auth/register/', userData)
}

export const getUserInfo = () => {
  return api.get('/auth/me/')
}

export const updateUserInfo = (userData: any) => {
  return api.patch('/auth/me/', userData)
}

export const refreshToken = () => {
  return api.post('/auth/refresh/')
}

// 图书相关API
export const getBooks = (params?: any) => {
  return api.get('/books/', { params })
}

export const getBookDetail = (id: number) => {
  return api.get(`/books/${id}/`)
}

export const searchBooks = (query: string) => {
  return api.get('/books/', { params: { search: query } })
}

// 购物车相关API
export const getCart = () => {
  return api.get('/cart/')
}

export const addToCart = (bookId: number, quantity: number = 1) => {
  return api.post('/cart/', { book: bookId, quantity })
}

export const updateCartItem = (itemId: number, quantity: number) => {
  return api.patch(`/cart/${itemId}/`, { quantity })
}

export const removeFromCart = (itemId: number) => {
  return api.delete(`/cart/${itemId}/`)
}

// 订单相关API
export const createOrder = (orderData: any) => {
  return api.post('/orders/', orderData)
}

export const getOrders = (params?: any) => {
  return api.get('/orders/', { params })
}

export const getOrderDetail = (id: number) => {
  return api.get(`/orders/${id}/`)
}

export const cancelOrder = (id: number) => {
  return api.post(`/orders/${id}/cancel/`)
}

export default api
